﻿using Common;
using FCT551.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FCT551.Helper
{
    /// <summary>
    /// 气缸运动
    /// </summary>
    public static class IoMotion
    {
        /// <summary>
        /// 进板气缸操作
        /// </summary>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static async Task<bool> MotionAirIn(int timeout = 3000)
        {
            var token = Global._EmgStopTokenSource.Token;
            //判断气缸状态
            Global._PqwIoCommon.GetDi();
            if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.下位磁开原点) && Global._PqwIoCommon.GetDi((int)CommonIODefineDi.上位磁开原点))
            {
                //下气缸上升
                bool res1 = await LowAirUp(timeout);
                token.ThrowIfCancellationRequested(); // 检查急停
                await Task.Delay(500);
                //上气缸下降
                bool res2 = await TopAirDown(timeout);
                token.ThrowIfCancellationRequested(); // 检查急停
                if (res1 == true && res2 == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 出板气缸操作
        /// </summary>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static async Task<bool> MotionAirOut(int timeout)
        {  //判断气缸状态
            var token = Global._EmgStopTokenSource.Token;
            Global._PqwIoCommon.GetDi();

            token.ThrowIfCancellationRequested(); // 检查急停
                                                  //上气缸上升
            bool res1 = await TopAirUp(timeout);
            // await Task.Delay(500);
            token.ThrowIfCancellationRequested(); // 检查急停
                                                  //下气缸下降
            bool res2 = await LowAirDown(timeout);
            token.ThrowIfCancellationRequested(); // 检查急停
            if (res1 == true && res2 == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 气缸停止操作
        /// </summary>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static void MotionAirStop()
        {
            Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀下压, true);
            Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀上升, true);
        }

        /// <summary>
        /// 上气缸上升
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> TopAirUp(int timeout)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool isok = false;
            try
            {
                //清空状态
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀下压, false);
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀上升, false);

                //发送下降信号
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀上升, true);

                await Task.Run(async () =>
                {
                    Stopwatch sw = Stopwatch.StartNew();
                    while (true)
                    {
                        token.ThrowIfCancellationRequested(); // 检查急停
                        Global._PqwIoCommon.GetDi();
                        if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.上位磁开原点))
                        {
                            //  Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀下压, true);
                            isok = true;
                            break;
                        }

                        if (sw.ElapsedMilliseconds > timeout)
                        {
                            break;
                        }

                        await Task.Delay(100);
                    }
                });
            }
            catch (Exception e)
            {
                MyLog.Error(e);
                return true;
            }

            return isok;
        }

        /// <summary>
        /// 上气缸下降
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> TopAirDown(int timeout)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool isok = false;
            try
            {
                //清空状态
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀上升, false);
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀下压, false);
                //发送下降信号
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀下压, true);
                Stopwatch sw = Stopwatch.StartNew();
                await Task.Run(async () =>
                {
                    while (true)
                    {
                        token.ThrowIfCancellationRequested(); // 检查急停
                        Global._PqwIoCommon.GetDi();
                        if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.上位磁开到位))
                        {
                            // Global._PqwIoCommon.SetDo((int)CommonIODefineDo.上位电磁阀上升, true);
                            isok = true;
                            break;
                        }

                        if (sw.ElapsedMilliseconds > timeout)
                        {
                            break;
                        }

                        await Task.Delay(100);
                    }
                });
            }
            catch (Exception e)
            {
                MyLog.Error(e);
                return true;
            }

            return isok;
        }

        /// <summary>
        /// 下气缸上升
        /// </summary>
        /// <returns></returns>

        public static async Task<bool> LowAirUp(long timeout)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool isok = false;
            try
            {
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.下位电磁阀, true);
                Stopwatch sw = Stopwatch.StartNew();
                await Task.Run(async () =>
                {
                    while (true)
                    {
                        token.ThrowIfCancellationRequested(); // 检查急停
                        Global._PqwIoCommon.GetDi();
                        if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.下位磁开到位))
                        {
                            isok = true;
                            break;
                        }

                        if (sw.ElapsedMilliseconds > timeout)
                        {
                            break;
                        }

                        await Task.Delay(100);
                    }
                });
            }
            catch (Exception e)
            {
                MyLog.Error(e);
                return true;
            }

            return isok;
        }

        /// <summary>
        /// 下气缸下降
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> LowAirDown(int timeout)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool isok = false;
            try
            {
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.下位电磁阀, false);
                Stopwatch sw = Stopwatch.StartNew();
                await Task.Run(async () =>
                {
                    while (true)
                    {
                        token.ThrowIfCancellationRequested(); // 检查急停
                        Global._PqwIoCommon.GetDi();
                        if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.下位磁开原点))
                        {
                            isok = true;
                            break;
                        }

                        if (sw.ElapsedMilliseconds > timeout)
                        {
                            break;
                        }

                        await Task.Delay(100);
                    }
                });
            }
            catch (Exception e)
            {
                MyLog.Error(e);
                return true;
            }

            return isok;
        }

        /// <summary>
        /// 挡板上升
        /// </summary>
        /// <returns></returns>

        public static async Task<bool> BlockAirUp(long timeout)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool isok = false;
            try
            {
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.挡板电磁阀, false);
                Stopwatch sw = Stopwatch.StartNew();

                while (true)
                {
                    token.ThrowIfCancellationRequested(); // 检查急停
                    Global._PqwIoCommon.GetDi();
                    if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.放板到位))
                    {
                        isok = true;
                        break;
                    }

                    if (sw.ElapsedMilliseconds > timeout)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                MyLog.Error(e);
                return true;
            }

            return isok;
        }

        /// <summary>
        /// 挡板下降
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> BlockAirDown(int timeout)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool isok = false;
            try
            {
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.挡板电磁阀, true);
                Stopwatch sw = Stopwatch.StartNew();
                await Task.Run(async () =>
                {
                    while (true)
                    {
                        token.ThrowIfCancellationRequested(); // 检查急停
                        Global._PqwIoCommon.GetDi();
                        if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.挡板原点))
                        {
                            isok = true;
                            break;
                        }

                        if (sw.ElapsedMilliseconds > timeout)
                        {
                            break;
                        }

                        await Task.Delay(100);
                    }
                });
            }
            catch (Exception e)
            {
                MyLog.Error(e);
                return true;
            }

            return isok;
        }

        /// <summary>
        /// 进板操作
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> MotionIn(int TimeOut = 6000)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool res = true;
            //挡板气缸下降
            await BlockAirDown(500);
            await Global.client.SendMessagesAsync("join");
            MotionRun();
            string msg = await Global.client.ReceiveRes();
            if (msg == "joinok")
            {
                //Stopwatch stopwatch = Stopwatch.StartNew();
                //while (true)
                //{
                //    token.ThrowIfCancellationRequested(); // 检查急停
                //    Global._PqwIoCommon.GetDi();
                //    if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.进板))
                //    {
                //        Stopwatch stopwatch2 = Stopwatch.StartNew();
                //        while (true)
                //        {
                //            token.ThrowIfCancellationRequested(); // 检查急停
                //            Global._PqwIoCommon.GetDi();
                //            if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.进板))
                //            {
                //                //当有到位信号的时候停止

                //                //可能需要自由配置
                //                await Task.Delay(2500);
                //                MotionStop();
                //                break;
                //            }
                //            if (stopwatch2.ElapsedMilliseconds > TimeOut)
                //            {
                //                MotionStop();
                //                //res = false;
                //                break;
                //            }
                //        }

                //        break;
                //    }
                //    if (stopwatch.ElapsedMilliseconds > TimeOut)
                //    {
                //        MotionStop();
                //        //res = false;
                //        break;
                //    }
                //}
                //进板新逻辑
                Stopwatch stopwatch = Stopwatch.StartNew();
                while (true)
                {
                    token.ThrowIfCancellationRequested(); // 检查急停
                    Global._PqwIoCommon.GetDi();
                    if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.到位))
                    {
                        //当有到位信号的时候停止

                        //可能需要自由配置
                        //await Task.Delay(2500);
                        MotionStop();
                        break;
                    }
                    if (stopwatch.ElapsedMilliseconds > TimeOut)
                    {
                        MotionStop();
                        res = false;
                        break;
                    }
                }

                //检测是否到位
                Global._PqwIoCommon.GetDi();
                if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.到位))
                {
                    res = false;
                }
            }
            else
            {
                res = false;
            }

            return res;
        }

        /// <summary>
        /// 出板操作
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> MotionOut(int TimeOut = 2000)
        {
            var token = Global._EmgStopTokenSource.Token;
            bool res = true;
            //挡板气缸上升
            await BlockAirUp(500);
            MotionRun();
            Stopwatch stopwatch = Stopwatch.StartNew();
            while (true)
            {
                token.ThrowIfCancellationRequested(); // 检查急停
                Global._PqwIoCommon.GetDi();
                if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.出板))
                {
                    //Stopwatch stopwatch2 = Stopwatch.StartNew();
                    //while (true)
                    //{
                    //    token.ThrowIfCancellationRequested(); // 检查急停
                    //    Global._PqwIoCommon.GetDi();
                    //    if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.出板))
                    //    {
                    //        //可能需要自由配置
                    //       await Task.Delay(600);
                    //        MotionStop();
                    //        break;
                    //    }
                    //    if (stopwatch2.ElapsedMilliseconds > TimeOut)
                    //    {
                    //        MotionStop();
                    //        //res = false;
                    //        break;
                    //    }
                    //}
                    await Task.Delay(1500);
                    MotionStop();

                    break;
                }
                if (stopwatch.ElapsedMilliseconds > TimeOut)
                {
                    MotionStop();
                    //res = false;
                    break;
                }
            }
            //检测是否出板
            Global._PqwIoCommon.GetDi();
            if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.出板))
            {
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 电机启动
        /// </summary>
        public static void MotionRun()
        {
            try
            {
                Global._YPF_Y40R_2.RunReverse();
                Global._YPF_Y40R_1.Run();
            }
            catch (Exception e)
            {
                MyLog.Error(e);
            }
        }

        /// <summary>
        /// 电机停止
        /// </summary>
        public static void MotionStop()
        {
            try
            {
                Global._YPF_Y40R_1.Stop();
                Global._YPF_Y40R_2.Stop();
            }
            catch (Exception e)
            {
                MyLog.Error(e);
            }
        }

        /// <summary>
        /// 关闭所有通道pwm信号
        /// </summary>
        public static void OffAllPwm()
        {
            Global._qjxPwm16?.SetALLStation(100);
            Global._qjxPwm4?.SetALLStation(100);
        }

        /// <summary>
        /// 设备报警
        /// </summary>
        public static void Error(int timeout)
        {
            try
            {
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.红灯, true);
                Thread.Sleep(timeout);
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.红灯, false);
            }
            catch (Exception e)
            {
                MyLog.Error(e);
            }
        }

        /// <summary>
        /// 设置绿灯
        /// </summary>
        public static void OK()
        {
            Global._PqwIoCommon.SetDo((int)CommonIODefineDo.绿灯, true);
        }
    }
}